<template>
	<!-- <div class="box-versions-form-page-container"> -->
	<ConfModuleContainer :show-page-tools="false">
		<template #Slot-Conf-Module-Header>
			<global-svg-icon
				icon-name="return"
				width="18px"
				height="18px"
				style="margin-right: 10px; vertical-align: middle; cursor: pointer"
				@click="router.go(-1)"
			/>
			<p class="version-title font-20-bold">版本上传</p>
		</template>
		<template #Slot-Conf-Module-Content>
			<div class="form-page">
				<div>
					<div class="title">
						<global-svg-icon icon-name="config-title-tri" width="3px" height="18px" style="vertical-align: middle" />
						<span class="text">版本上传</span>
					</div>
					<div class="form-main">
						<div class="main-body">
							<div class="form-box">
								<a-form ref="formRef" layout="horizontal" :model="formData">
									<div class="form-name">升级包名称*</div>
									<a-form-item
										style="padding-bottom: 40px"
										label-align="left"
										name="upPackageName"
										:rules="[{ required: true, message: '请输入升级包名称' }]"
									>
										<a-input v-model:value.trim="formData.upPackageName" style="width: 320px" :maxlength="10" placeholder="请输入" />
									</a-form-item>

									<div class="form-name">版本号*</div>
									<a-form-item
										style="padding-bottom: 40px"
										label-align="left"
										name="version"
										:rules="[{ required: true, message: '请输入版本号' }]"
									>
										<a-input v-model:value.trim="formData.version" disabled style="width: 320px" :maxlength="20" placeholder="请输入" />
									</a-form-item>

									<div class="form-name">类型*</div>
									<a-form-item
										style="padding-bottom: 40px"
										label-align="left"
										name="type"
										:rules="[{ required: true, message: '请选择类型' }]"
									>
										<a-radio-group v-model:value="formData.type">
											<a-radio value="1">固件</a-radio>
											<a-radio value="2">软件</a-radio>
										</a-radio-group>
									</a-form-item>

									<div class="form-name">上传升级包*</div>
									<a-form-item
										style="padding-bottom: 40px"
										label-align="left"
										name="address"
										:rules="[{ required: xxx, message: '请上传升级包' }]"
									>
										<!-- :validate-trigger="{ onChange }" -->
										<div class="upload-input">
											<a-upload
												multiple
												:show-upload-list="false"
												name="address"
												:custom-request="uploadRequest"
												:before-upload="handleBeforeUpload"
												:disabled="uploading"
												@remove="clearnFileX"
											>
												<a-button>
													<global-svg-icon icon-name="upload-2-line" width="16px" height="16px" style="margin-right: 6px" />
													上传升级包
												</a-button>
											</a-upload>
											<div v-if="file.name" class="file-wrap">
												<LoadingOutlined v-if="file.status === 'loading'" spin style="color: rgba(240, 246, 252, 0.2)" />
												<global-svg-icon v-if="file.status === 'success'" icon-name="success-line" width="20px" height="20px" />
												<global-svg-icon v-if="file.status === 'failed'" icon-name="failed-line" width="20px" height="20px" />
												<p class="file-name">{{ file.name }}</p>
												<global-svg-icon icon-name="close-circle-fill" class="delete-icon" width="20px" height="20px" @click="clearnFile" />
											</div>
											<div v-if="file.name" class="progress-box">
												<a-progress
													:stroke-color="{
														'0%': '#6188d0',
														'100%': '#223d82'
													}"
													size="small"
													stroke-linecap="square"
													:percent="percentage"
													:show-info="false"
												/>
											</div>
										</div>
									</a-form-item>

									<div class="form-name">描述</div>
									<a-form-item label-align="left" name="versionDescription">
										<a-textarea
											v-model:value.trim="formData.versionDescription"
											style="width: 320px"
											:maxlength="50"
											show-count
											:rows="4"
											placeholder="请输入"
										/>
									</a-form-item>
								</a-form>
							</div>
							<div style="margin-top: auto; padding-top: 34px">
								<a-button type="primary" :loading="loading" @click="saveForm">确定</a-button>

								<a-button ghost style="margin-left: 8px" class="btn-default" @click="router.go(-1)">取消</a-button>
							</div>
						</div>
					</div>
				</div>
			</div>
		</template>
	</ConfModuleContainer>

	<!-- </div> -->
</template>

<script setup lang="ts" name="roles-form">
import { FormInstance } from 'ant-design-vue';
import { LoadingOutlined } from '@ant-design/icons-vue';
import { g6RegValidate } from 'glasssix-utils-ts';
import httpServe from '@/global-services/index';
import { versionSoftWareReg, versionHardWareReg } from '@/global-utils/check';
import { TsVersionForm, TsFile } from '../../type';
import { ConfModuleContainer } from '../../components/index';
import { BoxVersionManageApi } from '../../api';

const router = useRouter();
const $message: any = inject('$message');
const formRef = ref<FormInstance>();
const loading = ref<boolean>(false);
const xxx = ref<boolean>(false);
let formData = reactive<TsVersionForm>({
	upPackageName: '',
	version: '',
	type: '1',
	multipartFile: '',
	versionDescription: '',
	address: ''
});

// 临时版本号
const version = ref<string>('');

// 提交表单
const saveForm = (): void => {
	loading.value = true;
	xxx.value = true;
	try {
		setTimeout(() => {
			formRef.value?.validate(['address']);
			console.log('---', formRef.value?.validate(['address']));
		}, 10);
		g6RegValidate.formSubmit(formRef.value, async () => {
			xxx.value = true;
			const param = {
				...formData
			};
			const res: TsRes = await BoxVersionManageApi.saveBoxVersionInfo(param);
			console.log('提交表单：', res);
			if (res.code === 0) {
				$message.success('版本上传成功');
				router.go(-1);
			}
		});
	} catch (error) {
		console.error(error);
	}
	console.log(formData);
	loading.value = false;
};

const file = reactive<TsFile>({
	name: '',
	status: ''
});
const uploading = ref<boolean>(false);
const percentage = ref<number>(0);

// 软件时：截取包名-之后的值作为版本号
const checkSoftWareVersion = (version: string): string => {
	const index = version.indexOf('-', version.indexOf('-') + 1);
	const result = version.substring(index + 1);

	return result;
};
// 上传前校验文件后缀
const handleBeforeUpload = (file: any): boolean | undefined => {
	const name = file.name.substring(0, file.name.lastIndexOf('.'));

	const type = file.name.split('.').at(-1).toLowerCase();
	let suffix = file?.name?.split('.')?.slice(-1)[0];
	if (formData.type === '1') {
		// 类型为固件时
		// console.log('version.value', version.value);

		if (suffix !== 'img' && suffix !== 'gz') {
			$message.error('仅支持tar.gz,img格式');
			return false;
		}
		if (!versionHardWareReg.test(name)) {
			$message.warning('文件名格式错误!');
			return false;
		}
		if (suffix === 'gz') {
			suffix = file?.name?.split('.')?.slice(-2)[0];
			if (suffix !== 'tar') {
				$message.error('仅支持tar.gz,img格式');
				return false;
			}
		}
		const index = name.indexOf('v', name.indexOf('-') + 1);
		const re = name
			.substring(index + 1)
			.split('.')
			.slice(0, 3);
		if (re[re.length - 1] === 'tar') {
			re.pop();
		}
		version.value = re.join('.');
		return true;
	}

	if (formData.type === '2') {
		// 类型为软件时
		if (type !== 'gz' && type !== 'jar' && type !== 'tar' && type !== 'zip') {
			$message.warning('请上传正确的版本包!');
			return false;
		}
		if (!versionSoftWareReg.test(name)) {
			$message.warning('文件名格式错误!');
			return false;
		}
		version.value = checkSoftWareVersion(name);
		return true;
	}
	return false;
};

// minIO上传接口
const uploadRequest = async (params: any): Promise<void> => {
	file.status = 'loading';
	file.name = params.file.name;
	uploading.value = true;
	const res: TsRes = await BoxVersionManageApi.getPresignedObjectUrl(file.name);
	formData.address = res.data.fileName;
	console.log('formData.address:262', formData.address);

	try {
		// 文件体上传接口
		const api = {
			upload: (data: any, url: string) =>
				httpServe.putHttp(url)(data, {
					headers: { customFlag: 'vesionUpload', 'Content-Type': 'application/x-www-form-urlencoded' },
					timeout: 5 * 60 * 1000,
					onUploadProgress: (progressEvent: any) => {
						percentage.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
					}
				})
		};
		await api.upload(params.file, res.data.url);
		file.status = 'success';
		formData.version = version.value;
	} catch (error) {
		$message.error('上传失败');
		console.log('error', error);
	} finally {
		formRef.value?.validate(['address']);
		formRef.value?.validate(['version']);
	}
};

// 清除上传包
const clearnFile = async (): Promise<void> => {
	formData.version = '';
	formRef.value?.resetFields(['clearValidate']);

	file.name = '';
	file.status = '';
	uploading.value = false;
	formData.multipartFile = '';
	console.log('formData.address:', formData.address);

	// minIO删除升级包
	if (formData.address) {
		const res: TsRes = await BoxVersionManageApi.deletePackage(formData.address);
		console.log('res', res);
		if (res?.code === 0) {
			formData.address = '';
			$message.success('删除成功');
		}
	}
};
const clearnFileX = (): void => {
	clearnFile();
	console.log('clearnFileX:', formData.address);

	formData.version = '';

	// formRef.value?.validateField(['address']);
};
// 切换类型时清空升级包

const watchStop = watch(
	() => formData.type,

	() => {
		clearnFile();
	}
);
const watchStop1 = watch(
	() => formData.upPackageName,
	() => {
		formData.upPackageName = formData.upPackageName.replace(/\s+/, '');
	}
);
onUnmounted(() => {
	watchStop();
	watchStop1();
});
</script>

<style lang="less" scoped>
.version-title {
	color: @text01;
}

.form-page {
	--role-header-height: 60px;
	--role-card-height: 400px;

	display: flex;
	overflow-y: auto;
	width: 100%;
	padding: 40px 0;
	padding-top: 12px;
	justify-content: center;

	.title {
		margin-bottom: 16px;

		.text {
			display: inline-block;
			margin-left: 8px;
			font-size: 16px;
			font-weight: 700;
			line-height: 24px;
			color: @text01;
		}
	}

	.form-main {
		display: flex;
		// height: 100%;
		// height: 696px;
		border: 1px solid @borderColor02;
		border-radius: 4px;
		// padding-bottom: 34px;
		background-color: @background02;
		box-shadow: 0 40px 180px 0 rgba(0, 0, 0, 0.35);
		flex-direction: column;

		.main-header {
			display: flex;
			height: var(--role-header-height);
			padding: 12px 20px;
			align-items: center;

			.back-btn {
				margin-right: 10px;
				margin-left: 10px;
				font-size: 24px;

				&:hover {
					opacity: 0.85;
					cursor: pointer;
				}
			}
		}

		.main-body {
			display: flex;
			width: 555px;
			height: 100%;
			padding: 20px 20px 40px;
			flex: 1;
			flex-direction: column;

			.form-box {
				.form-name {
					margin-bottom: 8px;
					line-height: 22px;
					color: @text02;
				}
				// 禁用项背景色
				.ant-input-disabled {
					background: @mask02 !important;

					&:focus-visible {
						border: transparent !important;
					}
				}

				.ant-form-item-control-input {
					input {
						height: 36px !important;
					}
				}

				.upload-input {
					.file-wrap {
						display: flex;
						width: 320px;
						height: 32px;
						margin-top: 12px;
						margin-bottom: 3px;
						border-radius: 3px;
						padding: 2px 4px;
						align-items: center;

						&:hover {
							border-radius: 4px;
							background-color: @mask03;
						}

						.file-name {
							margin: 0 10px;
							font-size: 14px;
							font-weight: 400;
							line-height: 22px;
							color: @text02;
							flex: 1;
						}

						.delete-icon {
							cursor: pointer;
						}
					}

					.progress-box {
						width: 401px;

						:deep(.ant-progress) {
							.ant-progress-outer {
								height: 2px !important;

								.ant-progress-inner {
									background: @mask02 !important;
								}

								.ant-progress-bg {
									height: 2px !important;
									border-radius: 6px !important;
								}
							}
						}
					}
				}
			}
		}
	}
}
</style>
